<?php

class lfApplication
{

	function __construct()
	{
		
		$config = parse_ini_file(PATH_ROOT . "/conf/framework.ini", TRUE);
		
		$this->confDefaultValue = $config["default_value"];
		$this->confDataBase = $config["database"];
		$this->_applicationName = $this->confDefaultValue["application_name"];
		$this->_moduleName = $this->confDefaultValue["modules_name"];
		$this->_controllerName = $this->confDefaultValue["controller_name"] . "Controller";
		$this->_methodName = $this->confDefaultValue["method_name"];
	}

	function Run($applicationName = "frontend")
	{
		if (file_exists(PATH_ROOT . '/applications/' . $applicationName . "/"))
			$this->_applicationName = $applicationName;
		else
			echo "application you provid doe's not exists";
		
		$this->ParseUrlInfo();
		require_once PATH_ROOT . "/applications/$applicationName/" . "controllers/$this->_moduleName" . '/' . $this->_controllerName . '.php';
		$_controllerName = $this->_controllerName;
		$_methodName = $this->_methodName;
		$_argsList = $this->_argsList;
		
		$controller = new $_controllerName();
		$exec = "return \$controller->\$_methodName($_argsList);";
		eval($exec);
	}

	/**
	 * 从URL中解析出系统运行所需要的信息
	 *
	 */
	function ParseUrlInfo()
	{
		$uri = $_SERVER['REQUEST_URI'];
		if (! defined("BASE_URL"))
		{
			echo "请定义BASE_URL";
		}
		
		if (BASE_URL != '/')
			$urlArgs = str_replace(BASE_URL, '', $uri);
		else
			$urlArgs = substr($uri, 1);
/* 用于处理Get 参数 服务器上自带参数，所以没用，等 服务器好了再去掉注释
		if (sizeof($_GET) > 0)
			$urlArgs = substr($urlArgs, 0, strpos($urlArgs, "?"));
*/	
		if (! empty($urlArgs))
		{
			$arUrlArgs = split('/', $urlArgs);
			
			$urlArgsCount = sizeof($arUrlArgs);
			$lastUrlArgs = $arUrlArgs[$urlArgsCount - 1];
			
			if (strpos($lastUrlArgs, "html"))
			{
				$this->_argsList = str_replace("-", "','", "'" . substr($lastUrlArgs, 0, strlen($lastUrlArgs) - 5) . "'");
				unset($arUrlArgs[$urlArgsCount - 1]);
			}
			
			$arModules = split('-', $arUrlArgs[0]);
			
			if ($arModules[0] != "")
				$this->_moduleName = $arModules[0];
			if ($arModules[1] != "")
				$this->_controllerName = ucfirst($arModules[1]) . "Controller";
			if ($arUrlArgs[1] != "")
				$this->_methodName = ucfirst($arUrlArgs[1]);
		
		}
	}

	function APP_NAME()
	{
		return $this->_applicationName;
	}

	function MODULE_NAME()
	{
		return $this->_moduleName;
	}

	function METHOD_NAME()
	{
		return $this->_methodName;
	}

	function DEFAULT_VALUE()
	{
		return $this->confDefaultValue;
	}

	function DATABASE_INFO()
	{
		return $this->confDataBase;
	}

	/**
	 * 创建应用程序类的维一对象
	 *
	 * @return lfApplication
	 */
	static function GetInstance()
	{
		global $___gApp___;
		if (is_null($___gApp___))
		{
			$___gApp___ = new lfApplication();
		}
		
		return $___gApp___;
	}
	
	private $confDefaultValue = array();
	private $confDataBase = array();
	
	private $_applicationName = "";
	private $_moduleName = "";
	private $_controllerName = "";
	private $_methodName = "";
	private $_argsList = "";
}

?>